<template>
	<div class="education-form">
		<a-form ref="formRef" :model="formModel" :rules="formRules" layout="vertical">
			<a-card title="教育经历" class="form-card">
				<div v-for="(education, index) in formData.educations" :key="index" class="education-item">
					<a-row :gutter="16">
						<a-col :span="24">
							<a-form-item
								:label="index === 0 ? '学历' : ''"
								:name="['educations', index, 'degree']"
								:rules="[{ required: true, message: '请选择学历' }]"
							>
								<a-select v-model:value="education.degree" placeholder="请选择学历">
									<a-select-option value="PRIMARY">小学</a-select-option>
									<a-select-option value="JUNIOR">初中</a-select-option>
									<a-select-option value="SENIOR">高中</a-select-option>
									<a-select-option value="JUNIOR_COLLEGE">大专</a-select-option>
									<a-select-option value="BACHELOR">本科</a-select-option>
									<a-select-option value="MASTER">硕士</a-select-option>
									<a-select-option value="DOCTOR">博士</a-select-option>
								</a-select>
							</a-form-item>
						</a-col>
					</a-row>

					<a-row :gutter="16">
						<a-col :span="24">
							<a-form-item
								:label="index === 0 ? '学校名称' : ''"
								:name="['educations', index, 'school']"
								:rules="[{ required: true, message: '请输入学校名称' }]"
							>
								<a-input v-model:value="education.school" placeholder="请输入学校名称" />
							</a-form-item>
						</a-col>
					</a-row>

					<a-row :gutter="16">
						<a-col :span="24">
							<a-form-item
								:label="index === 0 ? '专业' : ''"
								:name="['educations', index, 'major']"
								:rules="[{ required: true, message: '请输入专业' }]"
							>
								<a-input v-model:value="education.major" placeholder="请输入专业" />
							</a-form-item>
						</a-col>
					</a-row>

					<a-row :gutter="16">
						<a-col :span="12">
							<a-form-item
								:label="index === 0 ? '开始日期' : ''"
								:name="['educations', index, 'startDate']"
								:rules="[{ required: true, message: '请选择开始日期' }]"
							>
								<a-date-picker
									v-model:value="education.startDate"
									placeholder="请选择开始日期"
									style="width: 100%"
									picker="month"
									valueFormat="YYYY-MM"
								/>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item
								:label="index === 0 ? '结束日期' : ''"
								:name="['educations', index, 'endDate']"
								:rules="[{ required: true, message: '请选择结束日期' }]"
							>
								<a-date-picker
									v-model:value="education.endDate"
									placeholder="请选择结束日期"
									style="width: 100%"
									picker="month"
									valueFormat="YYYY-MM"
								/>
							</a-form-item>
						</a-col>
					</a-row>

					<a-row :gutter="16">
						<a-col :span="24">
							<a-form-item
								:label="index === 0 ? '是否全日制' : ''"
								:name="['educations', index, 'isFullTime']"
								:rules="[{ required: true, message: '请选择是否全日制' }]"
							>
								<a-radio-group v-model:value="education.isFullTime">
									<a-radio :value="true">是</a-radio>
									<a-radio :value="false">否</a-radio>
								</a-radio-group>
							</a-form-item>
						</a-col>
					</a-row>

					<div v-if="formData.educations.length > 1" class="remove-button">
						<a-button type="link" @click="removeEducation(index)">删除</a-button>
					</div>
				</div>

				<a-button type="dashed" block @click="addEducation">
					<PlusOutlined />
					添加教育经历
				</a-button>

				<a-form-item label="学历证书照片" name="diplomaImage">
					<a-upload
						v-model:file-list="diplomaImageList"
						list-type="picture-card"
						accept="image/jpeg,image/png"
						:multiple="true"
						:before-upload="beforeUpload"
						@change="handleChange"
						@preview="handlePreview"
						:showUploadList="{ showRemoveIcon: false }"
					>
						<div class="upload-btn">
							<plus-outlined />
							<div style="margin-top: 8px">上传照片</div>
						</div>
					</a-upload>
					<a-button @click="clearAllImages">清空</a-button>
					<div class="photo-count">已上传 {{ diplomaImageList.length }} 张照片</div>
				</a-form-item>
			</a-card>
		</a-form>

		<!-- 图片预览 -->
		<a-modal v-model:open="previewVisible" :footer="null" @cancel="previewVisible = false" class="image-preview-modal">
			<img alt="预览图片" :src="previewImageSrc" style="width: 100%" />
		</a-modal>
	</div>
</template>

<script setup>
	import { defineProps, nextTick, ref, watch } from 'vue'
	import { message } from 'ant-design-vue'
	import { PlusOutlined } from '@ant-design/icons-vue'
	import dayjs from 'dayjs'
	import onboardingRegistryApi from '@/api/hrms/onboarding/registry/onboardingRegistryApi'
	import Promise from 'lodash-es/_Promise'

	const props = defineProps({
		modelValue: {
			type: Object,
			default: () => ({})
		}
	})

	const formRef = ref()
	const previewVisible = ref(false)
	const previewImageSrc = ref('')
	const jdOssBaseUrl = 'https://s3.cn-north-1.jdcloud-oss.com/'

	// 表单数据模型
	const formModel = ref({
		educations: [],
		diplomaImage: [] // 添加 diplomaImage 字段到表单模型
	})

	// 表单数据
	const formData = ref({
		educations: []
	})

	// 学历证书文件列表
	const diplomaImageList = ref([])

	// 表单验证规则
	const formRules = {
		diplomaImage: [
			{
				required: true,
				validator: (rule, value, callback) => {
					if (diplomaImageList.value.length === 0) {
						return Promise.reject('请上传学历证书照片')
					} else {
						return Promise.resolve()
					}
				},
				trigger: 'change'
			}
		]
	}

	// 监听父组件传递的数据变化
	watch(
		() => props.modelValue,
		(newVal) => {
			if (newVal) {
				// 解析教育经历数据（新格式：education字段）
				if (Array.isArray(newVal.education)) {
					// 处理日期格式转换
					const educations = [...newVal.education]
					educations.forEach((education) => {
						if (education.startDate && typeof education.startDate === 'string') {
							education.startDate = dayjs(education.startDate)
						}
						if (education.endDate && typeof education.endDate === 'string') {
							education.endDate = dayjs(education.endDate)
						}
					})
					formData.value.educations = educations
					formModel.value.educations = educations // 同步更新表单模型
				} else {
					// 如果没有教育经历数据，则添加默认条目
					const defaultEducation = {
						degree: undefined,
						school: undefined,
						major: undefined,
						startDate: undefined,
						endDate: undefined,
						isFullTime: true // 默认全日制为true
					}
					formData.value.educations = [defaultEducation]
					formModel.value.educations = [defaultEducation] // 同步更新表单模型
				}

				// 初始化证书文件
				if (newVal.diplomaImage) {
					const fileNames = newVal.diplomaImage.split(',')
					diplomaImageList.value = fileNames.map((fileName, index) => ({
						uid: -index,
						name: fileName,
						status: 'done',
						url: `${jdOssBaseUrl}${fileName}`
					}))
				}
			}
		},
		{ immediate: true, deep: true }
	)

	// 添加教育经历
	const addEducation = () => {
		const newEducation = {
			degree: undefined,
			school: undefined,
			major: undefined,
			startDate: undefined,
			endDate: undefined,
			isFullTime: true // 默认全日制为true
		}
		formData.value.educations.push(newEducation)
		formModel.value.educations.push(newEducation) // 同步更新表单模型
	}

	// 删除教育经历
	const removeEducation = (index) => {
		if (formData.value.educations.length > 1) {
			formData.value.educations.splice(index, 1)
			formModel.value.educations.splice(index, 1) // 同步更新表单模型
		} else {
			message.warning('至少保留一条教育经历信息')
		}
	}

	const beforeUpload = (file) => {
		diplomaImageList.value = diplomaImageList.value.filter((item) => item.originFileObj)
		return false
	}

	const handleChange = ({ fileList: newFileList }) => {
		// 去重处理
		const uniqueFiles = []
		const seen = new Set()
		newFileList.forEach((file) => {
			const key = file.uid || file.name
			if (!seen.has(key)) {
				seen.add(key)
				uniqueFiles.push(file)
			}
		})
		diplomaImageList.value = uniqueFiles
	}

	const handlePreview = (file) => {
		previewImageSrc.value = file.url || file.thumbUrl
		previewVisible.value = true
	}

	const clearAllImages = () => {
		diplomaImageList.value = []
		nextTick(() => {
			formRef.value?.validateFields(['diplomaImage'])
		})
	}

	// 暴露保存数据方法给父组件调用
	defineExpose({
		saveData
	})

	// 保存数据方法（供父组件调用）
	async function saveData() {
		try {
			await formRef.value.validateFields()
			const submitData = formData.value.educations.map((education) => {
				const eduCopy = { ...education }
				// 将dayjs对象转换为字符串格式
				if (eduCopy.startDate && dayjs.isDayjs(eduCopy.startDate)) {
					eduCopy.startDate = eduCopy.startDate.format('YYYY-MM')
				}
				if (eduCopy.endDate && dayjs.isDayjs(eduCopy.endDate)) {
					eduCopy.endDate = eduCopy.endDate.format('YYYY-MM')
				}
				return eduCopy
			})
			const requestData = new FormData()
			// 添加JSON数据
			requestData.append(
				'onboardingRegistryEditBo',
				new Blob([JSON.stringify({ educationHistoryEditBoList: submitData })], {
					type: 'application/json'
				})
			)
			if (diplomaImageList.value.length > 0) {
				diplomaImageList.value.forEach((file) => {
					if (file.originFileObj) {
						requestData.append('multipartFileList', file.originFileObj)
					}
				})
			}
			await onboardingRegistryApi.updateRegistryInfo(props.modelValue.id, requestData)
			message.success('教育经历保存成功')
			return true
		} catch (error) {
			console.error('表单验证失败:', error)
			message.error('表单提交失败')
			return false
		}
	}
</script>

<style scoped>
	.form-card {
		margin-bottom: 16px;
		border-radius: 8px;
	}

	.form-card :deep(.ant-card-head) {
		background-color: #fafafa;
		border-radius: 8px 8px 0 0;
	}

	.education-item {
		position: relative;
		padding: 16px;
		border: 1px solid #f0f0f0;
		border-radius: 8px;
		margin-bottom: 16px;
	}

	.remove-button {
		text-align: right;
	}

	.photo-count {
		margin-top: 8px;
		font-size: 12px;
		color: #999;
	}

	.image-preview-modal :deep(.ant-modal-content) {
		padding: 0;
	}

	.image-preview-modal :deep(.ant-modal-body) {
		padding: 0;
	}
</style>
